﻿/*
 * Created by SharpDevelop.
 * User: Corrado Mio
 * Date: 13/06/2012
 * Time: 21:07
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Common;

namespace CSharpExt.Data
{
    /// <summary>
    /// Description of DataResultSet.
    /// </summary>
    public class DataResultSet : IEnumerable, IEnumerator
    {
        #region Private Data
        
        private DataCommand _dcmd;
        
        private DbDataReader _reader;
        
        private DataResultRow _row;
        
        private MetadataResultSet _meta;
        
        private Dictionary<String, int> _ordinals = new Dictionary<String, int>();
        
        #endregion
        
        #region Constructor 

        internal DataResultSet(DataCommand dcmd, DbDataReader reader)
        {
            _dcmd = dcmd;
            _reader = reader;
            _row = new DataResultRow(this);
        }

        #endregion
        
        #region Properties
        
        public DataCommand Command
        {
            get { return _dcmd; }
        }
        
        public MetadataResultSet Metadata
        {
            get 
            { 
                if (_meta == null)
                    _meta = new MetadataResultSet(this);
                return _meta; 
            }
        }
        
        // ------------------------------------------------------------------
        
        public bool IsClosed
        {
            get { return _reader.IsClosed; }
        }
        
        // ------------------------------------------------------------------
        
        internal DbDataReader InnerReader
        {
            get { return _reader; }
        }
        
        #endregion
        
        #region Operations
        
        public void Close()
        {
            _reader.Close();
            
            _dcmd.removeResultSet(this);
        }
        
        #endregion
        
        #region Interface Implementation
        
        public IEnumerator GetEnumerator()
        {
            return this;
        }

        public Object/*DataResultRow*/ Current 
        {
            get { return _row; }
        }
        
        public bool MoveNext()
        {
            return _reader.Read();
        }
        
        public void Reset()
        {
            throw new NotImplementedException();
        }
        
        
        // ------------------------------------------------------------------
        
        internal int ordinalOf(String name)
        {
            int ordinal;
            
            if(!_ordinals.TryGetValue(name, out ordinal))
            {
                ordinal = _reader.GetOrdinal(name);
                _ordinals[name] = ordinal;
            }
                
            return ordinal;
        }
        
        #endregion
    }
}
